package com.ebelter.temperaturegun.model;


import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Message;
import android.text.TextUtils;
import com.ebelter.btcomlib.models.bluetooth.base.BlueScan;
import com.ebelter.btcomlib.models.bluetooth.bean.ProductStyle;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IConnectStationCallback;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IScanCallback;
import com.ebelter.btcomlib.models.bluetooth.products.ear_temperature.EarTemperatureConstant;
import com.ebelter.btcomlib.models.bluetooth.products.temperature2.Temperature2Constant;
import com.ebelter.btcomlib.models.bluetooth.products.temperature2.Temperature2Manager;
import com.ebelter.btcomlib.models.bluetooth.products.temperature2.bean.TemMesureResult2;
import com.ebelter.btcomlib.models.bluetooth.products.temperature2.bean.TemMesureResult2His;
import com.ebelter.btcomlib.models.bluetooth.products.temperature2.interfaces.Temperature2MesureResult;
import com.ebelter.btcomlib.utils.BaseHandle;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.temperaturegun.TAppConfig;
import com.ebelter.temperaturegun.model.http.TgUpLoadDataUtil;
import java.math.BigDecimal;


public class TgManager extends BaseHandle{


    private static final String TAG = "TgManager";


    private Context mContext;

    private boolean startWorkFlag;//是否正在运行的标志
    private BlueScan mBlueScan;
    private Temperature2Manager mTemperature2Manager;//耳温枪管理器
    private TgUpLoadDataUtil mTgUpLoadDataUtil;

    /**
     * 当前需要连接的设备
     */
    private BluetoothDevice device;
    private Temperature2MesureResult mesuresCalBack;
    public void setMesuresCalBack(Temperature2MesureResult mesuresCalBack) {
        this.mesuresCalBack = mesuresCalBack;
    }

    public TgManager(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context) {
        this.mContext = context;
        mBlueScan=new BlueScan(mContext);
        mTemperature2Manager = new Temperature2Manager(context);
        mTemperature2Manager.setBlueConnectStationCallback(mConnectStationCallback);
        mTemperature2Manager.setTemperature2MeasureCallback(temperature2MesureResult);
        mTgUpLoadDataUtil = TgUpLoadDataUtil.getInstance();
    }


    public boolean isStartWorkFlag() {
        return startWorkFlag;
    }

    //连接回调器
    private final IConnectStationCallback mConnectStationCallback = new IConnectStationCallback() {
        @Override
        public void onConnected(ProductStyle productStyle, BluetoothDevice device) {
            if(device==null)return;
            String name = device.getName();//Belter_TP有额耳温的
            String address = device.getAddress();
            LogUtils.i(TAG, "--连接成功--onConnected--device.name = " + name + "---device.address = " + address);
            if (mTemperature2Manager!=null){
                mTemperature2Manager.setConnectedBluetoothName(name);
            }
            if (mesuresCalBack != null) {mesuresCalBack.onConnected(productStyle, device);}
            stopScan();


        }

        @Override
        public void onConnecting(ProductStyle productStyle, BluetoothDevice device) {
            if (mesuresCalBack != null) mesuresCalBack.onConnecting(productStyle, device);
        }

        @Override
        public void onDisConnected(ProductStyle productStyle) {
            LogUtils.i(TAG, "-------------连接断开");
            if (mesuresCalBack != null) mesuresCalBack.onDisConnected(productStyle);

            if (startWorkFlag){
                removeMessages(WHAT_AUTO_CHECK);
                sendEmptyMessage(WHAT_AUTO_CHECK);//当连接断开的时候 开始检测
            }

        }
    };


    private final Temperature2MesureResult temperature2MesureResult = new Temperature2MesureResult() {
        @Override
        public void mesureResult(TemMesureResult2 result) {
            if (mTemperature2Manager!=null)mTemperature2Manager.sendReceiveSuccessACK();
            if (mesuresCalBack != null) mesuresCalBack.mesureResult(result);
            if (!TAppConfig.isVisitorModel){
                mTgUpLoadDataUtil.add(result);//不是在访客模式下
            }

            mTgUpLoadDataUtil.start();

        }

        @Override
        public void mesureHisResult(TemMesureResult2His hisResult) {
            if (mesuresCalBack != null) mesuresCalBack.mesureHisResult(hisResult);
        }

        @Override
        public void error(String bluetoothName,int errorCode) {
            if (mesuresCalBack != null) mesuresCalBack.error(bluetoothName,errorCode);
        }

        @Override
        public void onDevicePoweroff() {
            if (mesuresCalBack != null) mesuresCalBack.onDevicePoweroff();
        }

        @Override
        public void setUnitSuccess() {
            if (mesuresCalBack != null) mesuresCalBack.setUnitSuccess();
        }

        @Override
        public void getHisDataFinish() {
            if (mesuresCalBack != null) mesuresCalBack.getHisDataFinish();
        }

        @Override
        public void getVersion(int versionCode) {
            if (mesuresCalBack != null) mesuresCalBack.getVersion(versionCode);
        }

        @Override
        public void onConnected(ProductStyle productStyle, BluetoothDevice device) {}

        @Override
        public void onConnecting(ProductStyle productStyle, BluetoothDevice device) {}

        @Override
        public void onDisConnected(ProductStyle productStyle) {}
    };

    //扫描蓝牙设备
    private void scanBlueDevices() {
        if (mBlueScan != null) {
            mBlueScan.stopScanBluetoothDevices();//先停止扫描
            mBlueScan.startScanBluetoothDevices(mScanCallback);//开始扫描
        }
    }


    private static final int WHAT_RESTART_SCAN = 1;
    private static final int WHAT_AUTO_CHECK = 2;
    @Override
    public void handleMsg(Message msg) {
        super.handleMsg(msg);
        if (msg.what == WHAT_RESTART_SCAN) {
            LogUtils.i(TAG, "---收到重新扫描的指令");
            scanBlueDevices();
        } else if (msg.what == WHAT_AUTO_CHECK) {
            removeMessages(WHAT_AUTO_CHECK);
            sendEmptyMessageDelayed(WHAT_AUTO_CHECK, 6000);
            autoCheck();
        }


    }

    //自动检测机制
    private void autoCheck() {


        LogUtils.i(TAG, "---自动检测机制正在运行--autoCheck（）");

        if (mTemperature2Manager == null) {
            LogUtils.i(TAG, "自动检测 mBaseManager = null 此次 return");
            return;
        }

        if (mTemperature2Manager.isConnect()) {
            LogUtils.i(TAG, "自动检测 设备--已经连接 此次return");
            return;
        }

        if (mBlueScan != null) {
            if (mBlueScan.isScaningFlag){
                LogUtils.i(TAG,"自动检测 扫描器正在扫描中 停止扫描");
                stopScan();
                //  return;
            }
            //能执行到这里 说明 设备没有连接中 并且没有扫描中
            LogUtils.i(TAG, "自动检测 设备没有连接中 准备重新扫描");
            scanBlueDevices();
        }


    }


    public void stopScan() {
        if (mBlueScan != null) {
            mBlueScan.stopScanBluetoothDevices();
        }
    }

    //扫描回调器
    private final IScanCallback mScanCallback = new IScanCallback() {
        @Override
        public void beforeScan() {
            LogUtils.i(TAG, "---beforeScan---");
            device = null;
        }

        @Override
        public void scanOneDevice(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            post(new Runnable() {
                @Override
                public void run() {
                    recordScanDevice(device);
                }
            });

        }

        @Override
        public void overScan() {
            LogUtils.i(TAG, "---扫描结束---");
//            if (device == null) {
//                //说明没有扫描成功 需要重新扫描
//                LogUtils.i(TAG, "---扫描结束 device = null 需要重新扫描");
//                removeMessages(WHAT_RESTART_SCAN);
//                sendEmptyMessageDelayed(WHAT_RESTART_SCAN, 1000);
//            }
        }
    };

    private void recordScanDevice(BluetoothDevice device) {
        if (device == null) {
            return;
        }
        String name = device.getName();
        String address = device.getAddress();
         LogUtils.i(TAG, "扫描到设备--Name = " + name + "---Addrss = " + address);
        if (TextUtils.isEmpty(name)||TextUtils.isEmpty(address)) {
            return;
        }
        //EE:86:1F:1F:A2:00
        //EE:86:1F:1F:29:CB
        //Belter_TP---device.address = 02:11:23:34:5A:A6
        //e-Thermometer---Addrss = E0:E5:CF:1F:5F:49
        if (name.contains(Temperature2Constant.Temperature2_NAME)
                ||Temperature2Constant.Temperature2_NAME.contains(name)
                ||name.contains(EarTemperatureConstant.EarTemperature_NAME)
                ||EarTemperatureConstant.EarTemperature_NAME.contains(name)
                ) {
            LogUtils.i(TAG, "--找到了需要连接的蓝牙设备------Name = " + name + "---Addrss = " + address + "---准备连接---");
            this.device = device;

            if (mBlueScan != null) {
                mBlueScan.exitScan();//退出扫描
            }
            connectBluetooth(device);//开始连接设备
        }
    }

    //连接蓝牙设备
    private void connectBluetooth(String address) {
        if (mTemperature2Manager != null) {
            mTemperature2Manager.connectDevice(address);
        }
    }

    //连接蓝牙设备
    private void connectBluetooth(BluetoothDevice bluetoothDevice) {
        if (mTemperature2Manager != null) {
            mTemperature2Manager.connectDevice(bluetoothDevice);
        }
    }

    //退出释放
    public void exitTgManager() {
        //01 释放蓝牙扫描器
        exit();
        if (mBlueScan != null) {
            if (mBlueScan.isScaningFlag) {
                mBlueScan.stopScanBluetoothDevices();
            }
            mBlueScan = null;
        }
        stopAutoCheck();
        if (mTemperature2Manager != null) {
            mTemperature2Manager.disConnect(false);
            mTemperature2Manager.exit();
            mTemperature2Manager = null;
        }
        mTgUpLoadDataUtil.stop();
        mTgUpLoadDataUtil=null;

    }
    public void stopAutoCheck() {
        removeMessages(WHAT_AUTO_CHECK);
        if (mBlueScan != null) {
            mBlueScan.stopScanBluetoothDevices();//停止扫描
        }
    }

    public void startWork() {
        if(startWorkFlag){
            LogUtils.i(TAG,"TgManager 已经处于运行状态 不需要重新运行");
            return;
        }
        if (!mTemperature2Manager.isConnect()){
            startWorkFlag=true;
            scanBlueDevices();//扫描设备
            startAutoCheck(6000);//开始自动检测
        }
    }

    public void stopWork() {
        if(!startWorkFlag){
            LogUtils.i(TAG,"TgManager 已经处于没有运行状态");
            return;
        }
        startWorkFlag = false;
        disConnectDevice(true);
        stopAutoCheck();
        stopScan();
    }

    private void startAutoCheck(long delayMillis) {
        removeMessages(WHAT_AUTO_CHECK);
        sendEmptyMessageDelayed(WHAT_AUTO_CHECK, delayMillis);
    }
    //断开连接 sendFront是否发给给前端的意思
    private void disConnectDevice(boolean sendFront) {
        if (mTemperature2Manager != null) mTemperature2Manager.disConnect(sendFront);
    }


    public void setUnitC(){
        if (mTemperature2Manager != null) mTemperature2Manager.setUnitC();
    }

    public void setUnitF(){
        if (mTemperature2Manager != null) mTemperature2Manager.setUnitF();
    }


    /**
     * <p>华氏度  = 32 + 摄氏度 × 1.8</p>
     * @param degree 需要转换的温度
     * @param scale 保留的小数位
     * @return
     */
//    public static double centigrade2Fahrenheit(double degree,int scale) {
//        double d = 32 + degree * 1.8;
//        return new BigDecimal(d).setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
//    }

    /**
     *
     * <p>摄氏度  = (华氏度 - 32) ÷ 1.8。</p>
//     * @param degree 需要转换的温度
//     * @param scale 保留的小数位
//     * @return
     */
    public static double fahrenheit2Centigrade(double degree, int scale) {
        double d = (degree - 32) / 1.8;
        return new BigDecimal(d).setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }


    public boolean isConnect(){
        return mTemperature2Manager!=null&&mTemperature2Manager.isConnect();
    }
}
